package eproject.mm.com.projectsupervision.service;


import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by momotea on 2018/5/23.
 */

public class MyJobService extends JobService {
    private final static String TAG = "MyJobService";

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = null;
    String curLat = "",curLng = "", localType = "";
    private OkHttpClient client;

    SharedPreferences userSettings;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            final Object obj = msg.obj;
            final String localStr = curLng + "," + curLat;
            final JobParameters param = (JobParameters) obj;
            PersistableBundle extBundle = param.getExtras();
            final String token = extBundle.getString("token");
            final String url = extBundle.getString("url");

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Request.Builder builder=new Request.Builder();
                        //String token = userSettings.getString("authenticationtoken","");
                        builder.addHeader("authenticationToken",token);
                        Request request=builder.get().url(url+"/insertPos?pos="+localStr+","+"&loctype=999").build();

                        Call call = HttpUtil.okHttpClient.newCall(request);
                        //同步GET请求
                        try {
                            Response response=call.execute();
                            //JobParameters param = (JobParameters) obj;
                            jobFinished(param, true);
                            Log.d(TAG, "jobFinished");
                        }catch (Exception e){
                            e.printStackTrace();
                            ///JobParameters param = (JobParameters) obj;
                            jobFinished(param, true);
                        }

                        Intent intent = new Intent(PrjApplication.getInstance().LocalAction);
                        sendBroadcast(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //JobParameters param = (JobParameters) obj;
                        jobFinished(param, true);
                    }finally {
                        mLocationClient.unRegisterLocationListener(myListener);
                        mLocationClient.stop();
                        myListener = null;
                        mLocationClient = null;
                    }
                }
            }).start();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");

        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "onStartJob");
        //userSettings = getApplicationContext().getSharedPreferences("setting", Context.MODE_MULTI_PROCESS);

        myListener = new MyLocationListener(params);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);

        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setWifiCacheTimeOut(5*60*1000);
        mLocationClient.setLocOption(option);

        mLocationClient.start();

        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        //停止，不是结束。jobFinished不会直接触发onStopJob
        //必须在“onStartJob之后，jobFinished之前”取消任务，才会在jobFinished之后触发onStopJob
        Log.d(TAG, "onStopJob");
        mHandler.removeMessages(0);
        return true;
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        JobParameters jobParameters;
        public MyLocationListener(JobParameters jobParameters){
            this.jobParameters = jobParameters;
        }
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            curLat = String.valueOf(latitude);
            curLng = String.valueOf(longitude);

            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明

            Log.d(TAG,"**************获取位置信息***********");

            Message message = Message.obtain();
            message.obj = jobParameters;
            mHandler.sendMessage(message);
        }
    }
}
